package com.symagic;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

import org.json.JSONException;
import org.json.JSONStringer;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.content.Intent;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnTouchListener;
import android.widget.ImageButton;
import android.widget.Toast;

import com.example.android.BluetoothChat.BluetoothChatService;
import com.example.android.BluetoothChat.DeviceListActivity;

public class SymagicActivity extends Activity {

	private ImageButton imageButtonJoin;
	private ImageButton imageButtonCreate;
	private ImageButton imageButtonQuit;

	public final static String IS_SERVER = "serverStyle";
	public final static int SERVER = 0;
	public final static int CLIENT = 1;
	public final static int NONEBLUETOOTH = -1;

	// bluetooth adapter
	private BluetoothAdapter bluetoothAdapter = null;

	/** Called when the activity is first created. */
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);

		// Get local Bluetooth adapter
		bluetoothAdapter = BluetoothAdapter.getDefaultAdapter();

		// If the adapter is null, then Bluetooth is not supported
		if (bluetoothAdapter == null) {
			Toast.makeText(this, R.string.BluetoothNotAvailable,
					Toast.LENGTH_LONG).show();
		}
		
		//create directory and data files
		createDirAndFiles();

		// Join a game
		imageButtonJoin = (ImageButton) findViewById(R.id.imageButtonJoin);
		// button animation.
		imageButtonJoin.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent eventStart) {
				if (eventStart.getAction() == MotionEvent.ACTION_DOWN) {
					imageButtonJoin.setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.joinbig));
				} else if (eventStart.getAction() == MotionEvent.ACTION_UP) {
					imageButtonJoin.setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.joinsmall));
				}
				return false;
			}
		});
		// Join button triger to open bluetooth and search if anyone create a
		// game.
		imageButtonJoin.setOnClickListener(new OnClickListener() {
			public void onClick(View V) {

				// if there is no blue tooth, do nothing
				if (bluetoothAdapter == null)
					return;

				// If BT is not on, request that it be enabled.
				if (!bluetoothAdapter.isEnabled()) {
					Intent enableIntent = new Intent(
							BluetoothAdapter.ACTION_REQUEST_ENABLE);
					startActivityForResult(enableIntent,
							BluetoothChatService.REQUEST_ENABLE_BT_CLIENT);
				} else {
					searchServer();
				}
			}
		});

		// Create a game
		imageButtonCreate = (ImageButton) findViewById(R.id.imageButtonCreate);
		// button animation.
		imageButtonCreate.setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent eventStart) {
				if (eventStart.getAction() == MotionEvent.ACTION_DOWN) {
					imageButtonCreate.setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.buildbig));
				} else if (eventStart.getAction() == MotionEvent.ACTION_UP) {
					imageButtonCreate.setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.buildsmall));
				}
				return false;
			}
		});
		// Create button trigger opening bluetooth and be able to be searched
		// for 300s,
		imageButtonCreate.setOnClickListener(new OnClickListener() {
			public void onClick(View V) {
				if (bluetoothAdapter != null) {
					// If bluetooth is not on, request that it be enabled.
					if (!bluetoothAdapter.isEnabled()) {
						Intent enableIntent = new Intent(
								BluetoothAdapter.ACTION_REQUEST_ENABLE);
						startActivityForResult(enableIntent,
								BluetoothChatService.REQUEST_ENABLE_BT_SERVER);
					} else {
						// if bluetooth is not discoverable, request for being
						// discoverable.
						if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
							Intent discoverableIntent = new Intent(
									BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
							discoverableIntent
									.putExtra(
											BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION,
											300);
							startActivityForResult(
									discoverableIntent,
									BluetoothChatService.REQUEST_ENABLE_BT_DISCOVER);
						}
						// if bluetooth is connectable and discoverable, then
						// create
						// a server,
						else {
							createServer();
						}
					}

				} 
				//debug jump
				else {
					
					Intent intent_build = new Intent(SymagicActivity.this,
							GameActivity.class);
					intent_build.putExtra(IS_SERVER, NONEBLUETOOTH);
					startActivity(intent_build);
					
				}
				//debug jump end

			}
		});

		// Quit this application
		imageButtonQuit = (ImageButton) findViewById(R.id.imageButtonQuit);
		// button animation.
		imageButtonQuit.setOnTouchListener(new OnTouchListener() {
			public boolean onTouch(View v, MotionEvent eventStart) {
				if (eventStart.getAction() == MotionEvent.ACTION_DOWN) {
					imageButtonQuit.setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.quitbig));
				} else if (eventStart.getAction() == MotionEvent.ACTION_UP) {
					imageButtonQuit.setBackgroundDrawable(getResources()
							.getDrawable(R.drawable.quitsmall));
				}
				return false;
			}
		});
		// Quit this game
		imageButtonQuit.setOnClickListener(new OnClickListener() {
			public void onClick(View V) {
				SymagicActivity.this.finish();
			}
		});
	}

	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		// TODO Auto-generated method stub
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {
		// return from bluetooth. weather open bluetooth or not.
		case BluetoothChatService.REQUEST_ENABLE_BT_SERVER:
			// see if bluetooth is enabled. if it isn't, then quit.
			if (!bluetoothAdapter.isEnabled()) {
				Toast.makeText(this,
						"You could play this game only if opened bluetooth!	",
						Toast.LENGTH_LONG).show();
				finish();
			} else if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
				// see if bluetooth is connectable and discoverable.
				// if it isn't discoverable, then ask user if turn it on for
				// 300s.
				Intent discoverableIntent = new Intent(
						BluetoothAdapter.ACTION_REQUEST_DISCOVERABLE);
				discoverableIntent.putExtra(
						BluetoothAdapter.EXTRA_DISCOVERABLE_DURATION, 300);
				startActivityForResult(discoverableIntent,
						BluetoothChatService.REQUEST_ENABLE_BT_DISCOVER);
			} else {
				// if it is connectable and discoverable. then create a new
				// game.
				createServer();
			}
			break;

		// Switch to DeviceListActivity to search for server.
		case BluetoothChatService.REQUEST_ENABLE_BT_CLIENT:
			// If user permit to turn on the bluetooth.
			if (!bluetoothAdapter.isEnabled()) {
				Toast.makeText(this,
						"You could play this game only if opened bluetooth!	",
						Toast.LENGTH_LONG).show();
				finish();
			} else {
				searchServer();
			}
			break;

		// return from request being discoverable.
		case BluetoothChatService.REQUEST_ENABLE_BT_DISCOVER:
			if (bluetoothAdapter.getScanMode() != BluetoothAdapter.SCAN_MODE_CONNECTABLE_DISCOVERABLE) {
				Toast.makeText(this,
						"U can only be discovered by peers which is paried !",
						Toast.LENGTH_SHORT);
			}
			createServer();
			break;

		}
	}

	private void createServer() {
		Intent intent_build = new Intent(SymagicActivity.this,
				GameActivity.class);
		intent_build.putExtra(IS_SERVER, SERVER);
		startActivity(intent_build);
	}

	private void searchServer() {
		Intent intent_imageStart = new Intent(SymagicActivity.this,
				DeviceListActivity.class);
		startActivity(intent_imageStart);
	}
	
	protected void createDirAndFiles(){
		File dir = new File("/data/data/com.symagic");
		if (!dir.exists()){
			dir.mkdirs();
		}
		
		//create relevant files and data
		File file = new File("/data/data/com.symagic/player_basic_msg.txt");
		if (!file.exists()){
			try {
				file.createNewFile();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
			//create Json data
			String dataStr = null;
			try {   
			    
			    JSONStringer player = new JSONStringer();  
			    player.object();
			    player.key("msgTypes");
			    player.value(GameActivity.INITIALIZE_DATA_MSG);
			    player.key("jing");
			    player.value(300);
			    player.key("qi");
			    player.value(0);
			    player.key("shen");
			    player.value(50);
			    player.key("attribute");
			    player.array();
			    player.value(3).value(3).value(3).value(3).value(3);
			    player.endArray();
			    player.endObject();
			    
			    dataStr = player.toString();
			} catch (JSONException ex) {    
			    throw new RuntimeException(ex);   
			}
			
			//write data in
			OutputStream outStream = null;
			try {
				outStream = new BufferedOutputStream(new FileOutputStream(file));
				try {
					outStream.write(dataStr.getBytes());
				} catch (IOException e) {
					// TODO Auto-generated catch block
					e.printStackTrace();
				}
			} catch (FileNotFoundException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} finally{
				if (outStream != null)
					try {
						outStream.flush();
						outStream.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
		}
	}

}
